package com.tgy.leetcode;

/**
 * @Author: tgy
 * @Date: 2020-11-25 09:28
 */
public class _75_颜色分类_02 {

    public void sortColors(int[] nums) {

        if (nums == null || nums.length <= 1) {

            return;
        }

        int left = 0,index = 0,right = nums.length - 1;

        /**
         * 注意这里要相等，用于判断 right 位置的元素
         */
        while (index <= right) {


            if (nums[index] == 0) {

//                if (left == index) {
//
//                    left++;
//                    index++;
//                }else {
//
//                    swap(nums,index,left);
//                    left++;
//                }
                swap(nums,index,left);
                index++;
                left++;
            }else if (nums[index] == 2) {

                swap(nums,index,right);
                right--;

            }else {

                index++;
            }

        }

    }

    private void swap(int[] nums,int i1, int i2) {

        if (i1 == i2) {
            return;
        }

        int tmp  = nums[i1];
        nums[i1] = nums[i2];
        nums[i2] = tmp;

    }

}
